package org.etlt.check;

import org.etlt.extract.Entity;
import org.etlt.extract.Extractor;
import org.etlt.job.JobContext;

import java.util.Objects;

public class E2VCheckPoint extends CheckPoint {

    public E2VCheckPoint(CheckPointSetting setting, CheckList checkList) {
        super(setting, checkList);
    }

    public CheckResult check(JobContext context) {
        CheckResult checkResult = new CheckResult(this);
        CheckPointSetting setting = getSetting();
        Extractor actualExtractor = context.createExtractor(setting.getActual());
        String expectedValue = setting.getExpected();
        actualExtractor.extract(context);
        Entity actualEntity = context.getEntity(setting.getActual());
        Object actualValue = actualEntity.getValue();
        if (Objects.equals(expectedValue, String.valueOf(actualValue)))
            checkResult.success();
        actualExtractor.extract(context);
        if (context.exists(setting.getActual()))
            checkResult.fail();
        return checkResult;
    }

    @Override
    public String getDetail(JobContext context) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getCheckList().getName())
                .append(".")
                .append(getName());
        stringBuilder.append(CR);
        stringBuilder.append("description: " + normalize(getSetting().getDescription()));
        stringBuilder.append(CR);
        stringBuilder.append("expected: " + getSetting().getExpected());
        stringBuilder.append(CR);
        Extractor actualExtractor = context.getExtractor(getSetting().getActual());
        stringBuilder.append("actual: " + actualExtractor);
        return stringBuilder.toString();
    }
}
